import { Toast } from 'mint-ui';

export default {
	// 将JSON字符串变成数组
	formatJSON(array, key) {
		return array.filter((item) => {
			if (item[key]) {
				item[key] = item[key].split(',');
			}
			return item;
		});
	},

	// 将JSON字符串变成JSON对象
	jsonToArr(str) {
		return JSON.parse(str);
	},

	// 将字符串变成字符串数组
	strToArr(str) {
		return str.split(',');
	},

	// 将逗号替换成空格
	replaceToSpace(str) {
		return str.replace(/,/g, ' ');
	},

	// 替换掉空格
	trimSpace(str) {
		return str.replace(/\s+/g, '');
	},

	// 节流函数
	throttle(fn, delay) {
		var t = null,
			begin = new Date().getTime();

		return function () {
			var _self = this,
				args = arguments,
				cur = new Date().getTime();

			clearTimeout(t);

			if (cur - begin >= delay) {
				fn.apply(_self, args);
				begin = cur;
			} else {
				t = setTimeout(function () {
					fn.apply(_self, args);
				}, delay);
			}
		}
	},

	//验证信息提示
	validate(key, keyValue) {

		// 验证规则
		const rules = {
			//手机号验证
			userTel: {
				rule: /^1\d{10}$/,
				msg: '手机号不能为空，且为11位数字'
			},
			//密码验证
			userPwd: {
				rule: /^\w{6,12}$/,
				msg: '密码不能为空，且要6-12位'
			},
			userCode: {
				rule: /^\d{4}$/,
				msg: '验证码不能为空，且为4位数字'
			}
		}

		let bool = true;
		if (!rules[key].rule.test(keyValue)) {
			//提示信息
			Toast(rules[key].msg);
			bool = false;
			return false;
		}
		return bool;
	},

	_addZero (value) {
  		return value < 10 ? ('0' + value) : value
	},

	// 格式化时间
	formatDateTime (timestamp) {
  		const date = new Date(timestamp);
		const y = date.getFullYear(),
				m = date.getMonth()+1,
				d = date.getDate(),
				h = this._addZero(date.getHours()),
				mi = this._addZero(date.getMinutes()),
				s = this._addZero(date.getSeconds());
		return `${y}年${m}月${d}日 ${h}:${mi}:${s}`;
	},

	// 去掉图片地址前的blob: 
	// blob: http://localhost:8081/13db2c4a-2eff-408f-916b-74323ff95200
	formatImgUrl(blobImgUrl) {
		return blobImgUrl.replace(/blob:/g, '');
	}
}





